package com.logic.landseaserver.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/*
 * Copyright 2005-2015 accommate.net. All rights reserved. Support: http://www.accommate.net License:
 * http://www.accommate.net/license
 */

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.Assert;

/**
 * Utils - Web
 * 
 * @author Logic Team
 * @version 4.0
 */
public final class WebUtils {

  /** CloseableHttpClient */
  private static final CloseableHttpClient HTTP_CLIENT;

  /** PoolingHttpClientConnectionManager */
  private static final PoolingHttpClientConnectionManager HTTP_CLIENT_CONNECTION_MANAGER;

  static {
    HTTP_CLIENT_CONNECTION_MANAGER = new PoolingHttpClientConnectionManager(RegistryBuilder
        .<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory())
        .register("https", SSLConnectionSocketFactory.getSocketFactory()).build());
    HTTP_CLIENT_CONNECTION_MANAGER.setDefaultMaxPerRoute(100);
    HTTP_CLIENT_CONNECTION_MANAGER.setMaxTotal(200);
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000)
        .setSocketTimeout(60000).build();
    HTTP_CLIENT = HttpClientBuilder.create().setConnectionManager(HTTP_CLIENT_CONNECTION_MANAGER)
        .setDefaultRequestConfig(requestConfig).build();
  }

  /**
   * GET请求
   * 
   * @param url
   *          URL
   * @param parameterMap
   *          请求参数
   * @return 返回结果
   */
  public static String get(String url, Map<String, Object> parameterMap) {
    Assert.hasText(url);

    String result = null;
    try {
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      if (parameterMap != null) {
        for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
          String name = entry.getKey();
          String value = ConvertUtils.convert(entry.getValue());
          if (StringUtils.isNotEmpty(name)) {
            nameValuePairs.add(new BasicNameValuePair(name, value));
          }
        }
      }
      HttpGet httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?")
          + EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
      CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpGet);
      try {
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
          result = EntityUtils.toString(httpEntity);
          EntityUtils.consume(httpEntity);
        }
      } finally {
        try {
          httpResponse.close();
        } catch (IOException e) {
        }
      }
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e.getMessage(), e);
    } catch (ParseException e) {
      throw new RuntimeException(e.getMessage(), e);
    } catch (ClientProtocolException e) {
      throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    return result;
  }
  public static String post(String url, Map<String, String> parameterMap) {
    Assert.hasText(url);

    String result = null;
    try {
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      if (parameterMap != null) {
        for (Map.Entry<String, String> entry : parameterMap.entrySet()) {
          String name = entry.getKey();
          String value = ConvertUtils.convert(entry.getValue());
          if (StringUtils.isNotEmpty(name)) {
            nameValuePairs.add(new BasicNameValuePair(name, value));
          }
        }
      }
      HttpPost httpPost = new HttpPost(url);
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
      CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpPost);
      try {
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
          result = EntityUtils.toString(httpEntity);
          EntityUtils.consume(httpEntity);
        }
      } finally {
        try {
          httpResponse.close();
        } catch (IOException e) {
        }
      }
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e.getMessage(), e);
    } catch (ClientProtocolException e) {
      throw new RuntimeException(e.getMessage(), e);
    } catch (ParseException e) {
      throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    return result;
  }
}